#include "daemon_sub_process.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/reboot.h>
#include <signal.h>

#define MAX_FAILED_COUNT 5 
#define GATEWAY_BIN "/usr/bin/gateway"
/**
 * @brief  初始化子进程
 * @param  pid  子进程的cmd
 * @return 子进程的结构体（子进程的句柄）
 */
sub_process_t *daemon_sub_process_init(char *cmd)
{
    sub_process_t *sub_process = (sub_process_t *)malloc(sizeof(sub_process_t));
    if (sub_process == NULL)
    {
        return NULL;
    }
    sub_process->pid = -1;
    sub_process->cmd = cmd;
    sub_process->failed_count = 0;

    return sub_process;
}

/** 
 * @brief  检查启动子进程
 * @param  sub_process 子进程的句柄
 * @return 0 成功，-1 失败
 */
int daemon_sub_process_check_and_start(sub_process_t *sub_process)
{  
    int  over_status =0;
    // 1 检查 waitpid   要么启动过 要么挂了
    if (sub_process->pid == -1 || waitpid(sub_process->pid, &over_status, WNOHANG) == -1)
    {
        if(over_status!=0)
        {  //横死
            sub_process->failed_count++;
            if(sub_process->failed_count>= MAX_FAILED_COUNT)
            {
                reboot(RB_AUTOBOOT); //重启
            }
        }
        // 启动子进程
        sub_process->pid = fork();
        if (sub_process->pid == 0)
        {
            // 子进程  执行execve 启动应用程序
            // 1. 运行子进程
             char *main_cmd=GATEWAY_BIN ;
             char *args[]={main_cmd,sub_process->cmd,NULL};
             char *envp[]={NULL};
             int ret=  execve(main_cmd,args,envp);
             if(ret==-1)
             {
                perror("execve");
                _exit(EXIT_FAILURE);
             }
             
        }

    }
    return 0;

}

/**
 * @brief  停止子进程
 */
void daemon_sub_process_stop(sub_process_t *sub_process)
{
    kill(sub_process->pid,SIGTERM);
    waitpid(sub_process->pid,NULL,0);
    printf("sub_process stop : %s\n" , sub_process->cmd);
}